package cjj.email;

import org.apache.commons.mail.DefaultAuthenticator;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.HtmlEmail;
import org.apache.commons.mail.SimpleEmail;

import java.nio.charset.Charset;


/**
 * @author chenjunjie
 * @since 2018-07-09
 */
public class HtmlMailDemo {

    public static void main(String[] args) {
        String email = "1131012589@qq.com";
        String title = "邮件测试";
        String content = "html email test";

       sendMail(email, title, content);
    }


    /**
     *
     * @param toAddress		收件人邮箱
     * @param mailSubject	邮件主题
     * @param mailBody		邮件正文
     * @return
     */
    public static boolean sendMail(String toAddress, String mailSubject, String mailBody){

        try {
            // Create the email message
            HtmlEmail email = new HtmlEmail();
            //SimpleEmail email = new SimpleEmail();

            //email.setDebug(true);		// 将会打印一些log
            //email.setTLS(true);		// 是否TLS校验，，某些邮箱需要TLS安全校验，同理有SSL校验
            //email.setSSL(true);

            email.setHostName("smtp.163.com");

            // isMailSSL()
            if (false) {
                email.setSslSmtpPort("25");
                email.setSSLOnConnect(true);
            } else {
                System.out.println("-----");
                email.setSmtpPort(Integer.valueOf("25"));
            }

            email.setAuthenticator(new DefaultAuthenticator("youaijj@163.com", "1WESDXCQAZ2"));
            email.setCharset(Charset.defaultCharset().name());

            email.setFrom("youaijj@163.com", "消息邮件推送平台");
            email.addTo(toAddress);
            email.setSubject(mailSubject);
            email.setMsg(mailBody);

            email.send();				// send the email
            return true;
        } catch (EmailException e) {
            System.out.println(e);
        }
        return false;
    }

}
